#include "data_analysis.h"
#include "ui_data_analysis.h"
#include "data_handle.h"
#include "sql_handle.h"
#include "login.h"

#include <QMessageBox>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlError>
#include <QtSql/QSqlQuery>
#include <QDebug>
#include <QDir>
#include <QCoreApplication>

data_analysis::data_analysis(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::data_analysis)
{
    ui->setupUi(this);
}

data_analysis::~data_analysis()
{
    delete ui;
}

void data_analysis::on_fresh_Button_clicked()
{
    sql_handle data;
    QSqlDatabase db = data.db;

    if (!db.isOpen()) {
        qDebug() << "Database connection is not open.";
        return;
    }

    QString user = QString::fromStdString(user_info.user);
    qDebug() << "User:" << user;

    QString queryStr = QString("SELECT SUM(sales) FROM %1").arg(user);

    QSqlQuery query(db);
    if (!query.exec(queryStr)) {
        qDebug() << "Query execution failed:" << query.lastError().text();
        return;
    }

    if (query.next()) {
        QVariant sumSales = query.value(0);
        if (sumSales.isValid()) {
            qDebug() << "Total sales:" << sumSales.toInt(); // 假设 sales 是整数类型
            ui->lineEdit->setText(QString::number(sumSales.toInt()));
            QMessageBox::information(this, "total", QString::number(sumSales.toInt()));
        } else {
            qDebug() << "No sales data found or SUM result is invalid.";
            ui->lineEdit->setText("0"); // 或者设置一个默认值
        }
    } else {
        qDebug() << "Query did not return any results.";
        ui->lineEdit->setText("0"); // 或者设置一个默认值
    }

}


void data_analysis::on_back_Button_clicked()
{
    data_handle *s = new data_handle;
    s->show();
    this->close();
}

